<?php 
/* $querystring = parse_url('http://mp3.zing.vn/album/Dut-Tung-Doan-Ruot-Luong-Bich-Huu/ZWZAE6EA.html', PHP_URL_QUERY);
parse_str($querystring, $vars);
echo '<pre>';
print_r($vars);
echo '</pre>'; */

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
	
	require_once 'libraries/function/validateAjax.php';

	
	$data = array();
	
	if($_GET['setNewAvatar'] == 1){
		$avatar = $_POST['newAvatar'];
		
		$tmpArray = explode('_', $avatar);
		$folder = $tmpArray[0] . '/' . $tmpArray[1] . '/' . $tmpArray[2] . '/';
		$agent = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15';
		$url = IMAGE_URL . 'avatar/original/' . $folder . $avatar;
		$url = str_replace(" ", '%20', $url);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_USERAGENT, $agent);
		curl_setopt($ch, CURLOPT_FAILONERROR, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_NOBODY, true);
		$result = curl_exec($ch);
		
		
		if($result !== false){
			$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			echo $statusCode;
			if($statusCode != 200){
				exit();
			}else{
				$model = new model();
				$model->where = "id = '" . $_SESSION['user']['id'] . "'";
				$data = array('avatar' => $avatar);
				$model->update('users', $data);
				
				$resultdel = file_get_contents(
					R_IMAGE_URL . 'avatar.php?file=' . urlencode($_SESSION['user']['avatar']), 
					false, 
					stream_context_create(array(
				        'http' => array(
				            'method' => 'DELETE' 
				        )
				    ))
				);
		
				$_SESSION['user']['avatar'] = $avatar;
			}
		}
	}
	
	if($_GET['validateTitle'] == 1){
		$validateAjax = new ValidateAjax();
		$validateAjax->validateTitle($_POST['txtTitle']);
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
		}else{
			echo json_encode(array('errors'=>''));
			
		}
		exit();
		
	}

	if($_GET['validateDescription'] == 1){
		$validateAjax = new ValidateAjax();
		$validateAjax->validateDescription($_POST['txtDescription'], array( 'validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
		}else{
			echo json_encode(array('errors'=>''));
			
		}
		exit();
	}
	
	/*
	 *  Validate image form
	 */
	
	if($_GET['validatePostImage'] == 1){

		$validateAjax = new ValidateAjax();
		$validateAjax->validateTitle($_POST['txtTitle']);
		$validateAjax->validateDescription($_POST['txtDescription'], array('validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));
		$validateAjax->validateFiles($_POST['uploadedFile']);
		
		
		$validateAjax->validateCategory($_POST['txtCat']);
		$validateAjax->validateAlbum($_POST['txtAlbum']);
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
			exit();
		}else{
			$datetime = date('Y-m-d H:i:s');
			$model = new Model();
			$table = 'post_image';
			$image = $_POST['uploadedFile'][0];
			unset($_POST['uploadedFile'][0]);
			
			$data = array(
					'title'				=> $_POST['txtTitle'],
					'description'		=> $_POST['txtDescription'],
					'cat_id'			=> $_POST['txtCat'],
					'album_id'			=> $_POST['txtAlbum'],
					'image'				=> $image,
					'date_created'		=> $datetime,
					'username'				=> $_SESSION['user']['username'],
					'status'			=> 1,
			);
			$model->insert($table, $data);
			
			$model->select = "id";
			$model->where = "username = '" . $_SESSION['user']['username'] . "'";
			$model->order = "id DESC";
			$model->limit = '1';
			$model->getdata('post_image');
			$result = $model->fetchOne();
			if($result){
				if(is_array($_POST['uploadedFile'])){
					foreach($_POST['uploadedFile'] as $file){
						$fileData = array(
									'post_id' => $result['id'],
									'image'		=> $file,
									'date_created'	=> $datetime
								);
						$model->insert('images', $fileData);
					}
				}
				
				$indexData = array(
							'post_id'	=> $result['id'],
							'is_image'	=> 1,
							'id_album'	=> $data['album_id'],
							'username'	=> $_SESSION['user']['username'],
							'status'	=> 1,
							'cat_id'	=> $_POST['txtCat']
						);
				$model->insert('index_post', $indexData);
				
				$model->select = "id";
				$model->order = "id DESC";
				$model->limit = "1";
				$model->getdata('index_post');
				$resultNewest = $model->fetchOne();
				if($resultNewest){
					file_put_contents(BASE_PATH . '/libraries/data/newest.txt', $resultNewest['id']);
				}
				
				
				
				echo json_encode(array('errors'=>'', 'message'=>'Đăng bài thành công.'));
				exit();
			}else{
				echo json_encode(array('errors'=>array('error'=>'Có lỗi xảy ra, xin vui lòng thử lại.'), 'message'=>''));
				exit();
			}
		}
	}
	
	/*
	 *  Validate video post
	 */
	if($_GET['validatePostVideo'] == 1){
	
		$validateAjax = new ValidateAjax();
		$validateAjax->validateTitle($_POST['txtTitle']);
		$validateAjax->validateDescription($_POST['txtDescription'], array('validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));

		$validateAjax->validateCategory($_POST['txtCat']);
		$validateAjax->validateAlbum($_POST['txtAlbum']);
		$video = $validateAjax->validateVideoSource($_POST['txtSourceUrl'], $_POST['txtSource']);

		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
			exit();
		}else{
			
			$datetime = date('Y-m-d H:i:s');
			$model = new Model();
			$table = 'post_media';
			$content = $video->getContent();

			//$image = $content['items'][0]['snippet']['thumbnails']['standard']['url'];
			
			$image = $video->getImage($content['items'][0]['snippet']['thumbnails']);

			$data = array(
					'title'				=> $_POST['txtTitle'],
					'description'		=> $_POST['txtDescription'],
					'media_type'		=> $video->_alias,
					'cat_id'			=> $_POST['txtCat'],
					'album_id'			=> $_POST['txtAlbum'],
					'url'				=> $_POST['txtSourceUrl'],
					'image'				=> $image,
					'date_created'		=> $datetime,
					'username'			=> $_SESSION['user']['username'],
					'status'			=> 1,
			);

			$model->insert($table, $data);
				
			$model->select = "id, album_id";
			$model->where = "username = '".$_SESSION['user']['username']."'";
			$model->order = "id DESC";
			$model->limit = '1';
			$model->getdata('post_media');
			$result = $model->fetchOne();
			if($result){
				if(is_array($_POST['uploadedFile'])){
					foreach($_POST['uploadedFile'] as $file){
						$fileData = array(
								'post_id' => $result['id'],
								'image'		=> $file,
								'date_created'	=> $datetime
						);
						$model->insert('images', $fileData);
					}
				}
	
				$indexData = array(
						'post_id'	=> $result['id'],
						'is_video'	=> 1,
						'status'	=> 1,
						'id_album'	=> $result['album_id'],
						'username'	=> $_SESSION['user']['username'],
						'cat_id'	=> $_POST['txtCat']
				);
				$model->insert('index_post', $indexData);
				
				$model->select = "id";
				$model->order = "id DESC";
				$model->limit = "1";
				$model->getdata('index_post');
				$resultNewest = $model->fetchOne();
				if($resultNewest){
					file_put_contents(BASE_PATH . '/libraries/data/newest.txt', $resultNewest['id']);
				}
				echo json_encode(array('errors'=>'', 'message'=>'Đăng bài thành công.'));
				exit();
			}else{
				echo json_encode(array('errors'=>array('error'=>'Có lỗi xảy ra, xin vui lòng thử lại.'), 'message'=>''));
				exit();
			}
		}
	}
	
	
	if($_GET['validatePostText'] == 1){
	
	
		$validateAjax = new ValidateAjax();
		$validateAjax->validateMainImage($_POST['txtMainImage']);
		$validateAjax->validateTitle($_POST['txtTitle']);
		$validateAjax->validateDescription($_POST['txtDescription'], array('validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));

	
	
		$validateAjax->validateCategory($_POST['txtCat']);
		$validateAjax->validateAlbum($_POST['txtAlbum']);
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
			exit();
		}else{
			
			$surl="content=".urlencode($_POST['txtDescription']);
			$url = IMAGE_URL . 'text/image.php';
			$resultContent = mycurl($surl,$url);
			$_POST['txtDescription'] = urldecode($resultContent);

			$datetime = date('Y-m-d H:i:s');
			$model = new Model();
			$table = 'post_text';
			$image = $_POST['txtMainImage'];
			$data = array(
					'title'				=> $_POST['txtTitle'],
					'description'		=> $_POST['txtDescription'],
					'cat_id'			=> $_POST['txtCat'],
					'album_id'			=> $_POST['txtAlbum'],
					'image'				=> $image,
					'date_created'		=> $datetime,
					'username'			=> $_SESSION['user']['username'],
					'status'			=> 1,
			);
			$model->insert($table, $data);
				
			$model->select = "id";
			$model->where = "username = '" . $_SESSION['user']['username'] . "'";
			$model->order = "id DESC";
			$model->limit = '1';
			$model->getdata('post_text');
			$result = $model->fetchOne();

			if($result){
				if(is_array($_POST['uploadedFile'])){
					foreach($_POST['uploadedFile'] as $file){
						$fileData = array(
								'post_id' => $result['id'],
								'image'		=> $file,
								'date_created'	=> $datetime
						);
						$model->insert('images', $fileData);
					}
				}
	
				$indexData = array(
						'post_id'	=> $result['id'],
						'is_text'	=> 1,
						'status'	=> 1,
						'username'	=> $_SESSION['user']['username'],
						'cat_id'	=> $_POST['txtCat'],
						'id_album'	=> $_POST['txtAlbum']
				);
				$model->insert('index_post', $indexData);
				
				$model->select = "id";
				$model->order = "id DESC";
				$model->limit = "1";
				$model->getdata('index_post');
				$resultNewest = $model->fetchOne();
				if($resultNewest){
					file_put_contents(BASE_PATH . '/libraries/data/newest.txt', $resultNewest['id']);
				}
				
				echo json_encode(array('errors'=>'', 'message'=>'Đăng bài thành công.'));
				exit();
			}else{
				echo json_encode(array('errors'=>array('error'=>'Có lỗi xảy ra, xin vui lòng thử lại.'), 'message'=>''));
				exit();
			}
		}
	}
	
	if($_GET['createAlbum'] == 1){
		$validateAjax = new ValidateAjax();
		$validateAjax->validateAlbumTitle($_POST['txtAlbumTitle']);
		$validateAjax->validateDescription($_POST['txtAlbumDescription'], array('validateAlias'=>'txtAlbumDescription', 'validateDescription' => 'Mô tả album'));
		if($validateAjax->isError()){
			$errors = $validateAjax->getErrorMessages();
			echo json_encode($errors);
			exit();
		}else{
			$model = new Model();
			$table = 'album';
			$data = array(
					'name' =>	$_POST['txtAlbumTitle'],
					'username'	=> $_SESSION['user']['username'],
					'date_created'	=>	date('Y-m-d H:i:s'),
					'description'	=> $_POST['txtAlbumDescription']
					);
			$model->insert($table, $data);
			echo json_encode(array('errors'=>'', 'message' => 'Tạo album mới thành công.'));
			exit();
		}
	}
	
	if($_GET['reloadAlbum'] == 1){
		
		
		
		$model = new Model();
		$model->select = 'id, name';
		$model->where = "";
		$model->getdata('album');
		$result = $model->fetchAll();
		
		$model->select = 'id';
		$model->order = 'id DESC';
		$model->limit = 1;
		$model->getdata('album');
		$resultLastest = $model->fetchOne();
		
		if($result){
			$return='<option  value="">Tùy Chọn Album ...</option>';
			foreach($result as $key => $value){
				if($resultLastest){
					if($resultLastest['id'] == $value['id']){
						$return .= '<option selected value="'.$value['id'].'">'.$value['name'].'</option>';
					}else{
						$return .= '<option value="'.$value['id'].'">'.$value['name'].'</option>';
					}
				}
				
			}
		}
		echo $return;
		exit();
	}
	
	
	/*
	 *  Return html form for creating album on the modal box
	 */
	
	if($_GET['albumBox'] == 1){
		echo returnAlbumBox();
	}
	
}

function returnAlbumBox(){
	return '
	<div role="dialog" id="modalAlbumBox" class="modal fade" style="display: none;">
		<div class="modal-dialog modal-wide">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
					<h4 class="modal-title">Tạo Album mới</h4>
				</div>
		        <div class="modal-body">
					<div>
						<input type="text" class="form-control" id="txtAlbumTitle" placeholder="Tên album..." />
					</div>
					<br />
					<div>
						<textarea class="form-control" id="txtAlbumDescription" placeholder="Mô tả album..."></textarea>
					</div>
					<br />
					<div>
						<button type="submit" class="btn btn-primary btn-sm" id="sumbmitAlbum">
	                    	<i class="glyphicon glyphicon-plus"></i>
		                    <span>Tạo</span>
		                </button>
					</div>
					<div style="clear:both"></div>
		        </div>
			</div><!-- /.modal-content -->
		</div>
			
		<script type="text/javascript">
			$(document).ready(function(){
				$("#sumbmitAlbum").on("click", function(e){
					$("#modalAlbumBox").find(".alert").remove();
					e.preventDefault();
					$.ajax({
						url : "index.php?module=user&act=ajax&createAlbum=1",
						type: "POST",
						data: {txtAlbumTitle: $("#txtAlbumTitle").val(), txtAlbumDescription : $("#txtAlbumDescription").val()},
						success: function(data){
							if(data) { 
								newData = $.parseJSON(data); 
								if(newData.errors){
									$.each(newData.errors, function(index, error){
										$("#" + index).parent().append("<div id=\'"+index+"_error\' class=\'alert alert-danger alert-dismissable\' style=\'display: none;\'><button type=\'button\' class=\'close\' data-dismiss=\'alert\' aria-hidden=\'true\'>&times;</button><strong>Lỗi!</strong>"+ error + "</div>");
										$("#" + index + "_error").slideDown("fast");
									});
								}else{
									if(newData.message){
										$.ajax({
											url: "index.php?module=user&act=ajax&reloadAlbum=1",
											type: "POST",
											success: function(dataAlbum){
												$("#txtAlbum").html(dataAlbum);
												$("#txtAlbum").select2({ width: "250" });
											},
										});
										$("#txtAlbum").html("");
										$("#modalAlbumBox").modal("hide");
										$("#txtAlbum").parent().append("<div id=\'txtAlbum_message\' class=\'alert alert-success alert-dismissable\' style=\'display: none;\'><button type=\'button\' class=\'close\' data-dismiss=\'alert\' aria-hidden=\'true\'>&times;</button>"+ newData.message + "</div>");
										$("#txtAlbum_message").slideDown("fast");
									}
								}
							}
						},
					});
				});
			});
			
		</script>
		
	</div>';
	
}

function returnVideoForm(){
	return
	'<form id="videoPostForm" class="userPostForm" role="form">
		
		<div class="form-group">	
			<div class="field_error" id="txtCat_error></div>
			<label for="txtCat">Danh mục:</label>
			<select id="txtCat" class="myNormalSelect">
				<option value="">Hài</option>	
				<option value="">Buồn</option>	
				<option value="">Bựa</option>	
				<option value="">Lãng mạng</option>	
			</select>
		</div>	<br />
			
		<div class="form-group">
			<div class="field_error" id="txtTitle_error></div>
			<label for="txtTitle">Tiêu đề:</label>
			<input type="text" class="form-control" id="txtTitle" placeholder="Nhập tiêu đề">
		</div><br />

		<div class="form-group">
			<div class="field_error" id="txtvideoUrl_error></div>
			<label for="txtvideoUrl">Video URL:</label>
			<input type="text" class="form-control" id="txtvideoUrl" placeholder="Nhập url">
		</div><br />

		<div class="form-group">
			<button type="submit" class="btn btn-primary">Đăng bài</button>
		</div>
	</form>';
}

function returnTextForm(){
	return
	'<form id="" class="userPostForm" role="form">
			
		<div class="form-group">	
			<div class="field_error" id="txtCat_error></div>
			<label for="txtCat">Danh mục:</label>
			<select id="txtCat" class="myNormalSelect">
				<option value="">Hài</option>	
				<option value="">Buồn</option>	
				<option value="">Bựa</option>	
				<option value="">Lãng mạng</option>	
			</select>
		</div>	<br />
			
		<div class="form-group">
			<div class="field_error" id="txtTitle_error></div>
			<label for="txtTitle">Tiêu đề:</label>
			<input type="text" class="form-control" id="txtTitle" placeholder="Nhập tiêu đề">
		</div><br />

		<div class="form-group">
			<div class="field_error" id="txtContent_error></div>
			<label for="txtContent">Nội dung:</label>
			<textarea class="form-control" rows="5" id="txtContent" placeholder="Nhập nội dung bài viết"></textarea>
		</div><br />
			
		<div class="form-group">
			<button type="submit" class="btn btn-primary">Đăng bài</button>
		</div>
	</form>';
}


